package com.es.spring.aop.interceptor;

import com.es.spring.aop.common.TargetMethod;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 二十
 * @since 2021/11/9 10:51 下午
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JdkDynamic implements InvocationHandler {

    Object target;

    List<MyInterceptor> interceptors = new ArrayList<>();

    public void add(MyInterceptor interceptor){
        interceptors.add(interceptor);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return new MyInvocationHandler(interceptors,new TargetMethod(target,method,args)).proceed();
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
    }

}
